<template>
  <!-- 在页面顶部或底部添加加载遮罩 -->
  <div v-loading="submitting" class="sales-contract-detail-container">
    <div class="sales-contract-detail-container">
      <!-- Document Information Group -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <span class="title-text">单据信息</span>
              <span class="store-name">{{ salesContract.storeName }}</span>
              <el-tag v-if="!this.editMode"
                :type="salesContract.status.code === CommonOrderStatus.Passed.code ? 'success' : 'info'" size="small"
                class="status-tag">
                {{ salesContract.status.name }}
              </el-tag>
            </div>
            <!-- Action Buttons -->
            <div class="action-buttons" v-if="!this.editMode">
              <el-button plain @click="handleCopy">
                <el-icon>
                  <CopyDocument />
                </el-icon> 复制
              </el-button>
              <el-button plain @click="handlePrint" style="margin-right: 20px">
                <el-icon>
                  <Printer />
                </el-icon> 打印
              </el-button>
              <el-button v-if="SalesContract.hasEditPermission()" type="primary" plain @click="handleEdit">
                <el-icon>
                  <Edit />
                </el-icon> 编辑
              </el-button>
              <el-button v-if="SalesContract.hasEditPermission()" type="danger" plain @click="handleDelete">
                <el-icon>
                  <Delete />
                </el-icon> 删除
              </el-button>
            </div>
          </div>
        </template>
        <el-form ref="ruleFormRef" :model="formData" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="6">
              <input-widget-web v-model="formData.title" label="单据标题" prop="title" :readonly="!this.editMode" />
            </el-col>
            <el-col v-if="!this.editMode" :span="6">
              <input-widget-web v-model="formData.docCode" label="单据编号" prop="docCode" :readonly="!this.editMode" />
            </el-col>

            <el-col :span="6">
              <partner-select v-model="formData.targetObject" label="客户" prop="targetObject" :readonly="!this.editMode"
                initialPartnerType="customer" :rules="[{ required: true, message: '请选择客户', trigger: 'blur' }]"
                :basicUiAction="basicUiAction" />
            </el-col>

            <el-col :span="6">
              <warehouse-select v-model="formData.warehouse" label="仓库" prop="warehouse" :readonly="!this.editMode"
                :inventoryUiAction="inventoryUiAction" />
            </el-col>

            <el-col :span="6">
              <date-time-select v-model="formData.operateDate" label="销售日期" prop="operateDate"
                :readonly="!this.editMode" type="datetime" />
            </el-col>

            <el-col :span="6">
              <employee-select v-model="formData.operator" label="经办人" prop="operator" :readonly="!this.editMode"
                :enterpriseMgtUiAction="enterpriseMgtUiAction" />
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- Sales Items Group -->
      <el-card class="items-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <div class="summary-container">
                <span class="title-text">销售商品</span>
                <span class="total-info">
                  共{{ salesContract.commmodityList.length }}件商品
                </span>
              </div>
              <!-- 添加和删除按钮 -->
              <div v-if="editMode" class="action-buttons">
                <el-button type="primary" size="small" @click="handleAddCommodity">
                  添加商品
                </el-button>
                <el-button type="danger" size="small" @click="handleDeleteSelectedCommodities">
                  删除商品
                </el-button>
              </div>
            </div>
          </div>
        </template>

        <el-table :data="salesContract.commmodityList" style="width: 100%" @selection-change="handleSelectionChange">
          <!-- 勾选列 -->
          <el-table-column type="selection" width="55" v-if="editMode" />
          <el-table-column label="图片" width="150">
            <template #default="scope">
              <el-image v-if="scope.row.commodity.imgs" :src="scope.row.commodity.imgs.split(',')[0]" fit="cover"
                class="commodity-image"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="180">
            <template #default="scope">
              {{ scope.row.commodity.name }}
            </template>
          </el-table-column>
          <el-table-column label="规格" width="180">
            <template #default="scope">
              {{ scope.row.commodity.standard }}
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80">
            <template #default="scope">
              {{ scope.row.commodity.unit?.name || '-' }}
            </template>
          </el-table-column>

          <el-table-column label="数量" align="right" width="100">
            <template #default="scope">
              <input-cell :readonly="!editMode" :model-value="scope.row.count.value" :numberMode="true"
                :precision="countPrecision"
                @update:model-value="val => { scope.row.setCount(new CsDouble(val, countPrecision)); salesContract.calculatePriceAndQuantity(); }" />

            </template>
          </el-table-column>

          <el-table-column label="单价" align="right" width="100">
            <template #default="scope">
              <input-cell :readonly="!editMode" :model-value="scope.row.singlePrice.value" :numberMode="true"
                :precision="fundPrecision"
                @update:model-value="val => {scope.row.setSinglePrice(new CsFundDouble(val)); salesContract.calculatePriceAndQuantity();}" />
            </template>
          </el-table-column>

          <el-table-column label="折扣%" align="right" width="100">
            <template #default="scope">
              <input-cell :readonly="!editMode" :model-value="scope.row.discount.value" :numberMode="true"
                :precision="disCountRation"
                @update:model-value="val => {scope.row.discount = new CsDouble(val, disCountRation); salesContract.calculatePriceAndQuantity();}" />
            </template>
          </el-table-column>

          <el-table-column label="折后总价" align="right" width="100">
            <template #default="scope">
              <input-cell :readonly="!editMode" :model-value="scope.row.batchPriceWithDiscount.value" :numberMode="true"
                :precision="fundPrecision"
                @update:model-value="val => {scope.row.setBatchPriceWithDiscount(new CsFundDouble(val, fundPrecision)); salesContract.calculatePriceAndQuantity();}" />
            </template>
          </el-table-column>

          <el-table-column label="税率(%)" align="right" width="100">
            <template #default="scope">
              <input-cell :readonly="!editMode" :model-value="scope.row.taxRate.value" :numberMode="true" :precision="2"
                @update:model-value="val => {scope.row.taxRate = new CsDouble(val, 2); salesContract.calculatePriceAndQuantity();}" />
            </template>
          </el-table-column>

          <el-table-column label="含税单价" align="right" width="100">
            <template #default="scope">
              <input-cell :readonly="!editMode" :model-value="scope.row.singlePriceAfterTax.value" :numberMode="true"
                :precision="fundPrecision"
                @update:model-value="val => {scope.row.setSinglePriceAfterTax(new CsFundDouble(val, fundPrecision)); salesContract.calculatePriceAndQuantity();}" />
            </template>
          </el-table-column>

          <el-table-column label="税额" align="right" width="100">
            <template #default="scope">
              <input-cell :readonly="true" :model-value="scope.row.tax.value" :numberMode="true"
                :precision="fundPrecision" />
            </template>
          </el-table-column>

          <el-table-column label="含税总价" align="right" width="100">
            <template #default="scope">
              <input-cell :readonly="!editMode" :model-value="scope.row.batchPriceWithTax.value" :numberMode="true"
                :precision="fundPrecision"
                @update:model-value="val => {scope.row.setBatchPriceWithTax(new CsFundDouble(val, fundPrecision)); salesContract.calculatePriceAndQuantity();}" />
            </template>
          </el-table-column>



          <el-table-column label="赠品" align="right" width="120">
            <template #default="scope">
              <span>{{ scope.row.isPromotional ? "是" : "否" }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-row :gutter="16" class="summary-row">
        <el-col :span="12">
          <el-card class="amount-summary-card" shadow="never">
            <template #header>
              <div class="card-header">
                <div class="title-wrapper">
                  <span class="title-text">金额汇总</span>
                </div>
              </div>
            </template>

            <div class="amount-summary-content">
              <div class="amount-item">
                <span class="label right-align">商品金额:</span>
                <span class="value left-align">{{ formatCurrency(salesContract.commodityPriceWithTax.value) }}</span>
              </div>
              <div class="amount-item">
                <span class="label right-align">整单折扣率(%):</span>
                <div class="value left-align">
                  <input-cell :width="'200px'" :readonly="!editMode" :model-value="salesContract.discountRatio.value"
                    :numberMode="true" :precision="disCountRation"
                    @update:model-value="val => salesContract.discountRatio = new CsDouble(val, disCountRation)" />
                </div>
              </div>
              <div class="amount-item">
                <span class="label right-align">折后优惠:</span>
                <div class="value left-align">
                  <input-cell :width="'200px'" :readonly="!editMode" :model-value="salesContract.discount.value"
                    :numberMode="true" :precision="fundPrecision"
                    @update:model-value="val => salesContract.discount = new CsFundDouble(val, fundPrecision)" />
                </div>
              </div>

              <div class="amount-item">
                <span class="label right-align">其他费用:</span>
                <div class="value left-align">
                  <input-cell :width="'200px'" :readonly="!editMode" :model-value="salesContract.otherCost.value"
                    :numberMode="true" :precision="fundPrecision"
                    @update:model-value="val => salesContract.otherCost = new CsFundDouble(val, fundPrecision)" />
                </div>
              </div>

              <div class="amount-item">
                <span class="label right-align">抹零:</span>
                <value-checkbox-widget class="value left-align"
                  :display-text="formatCurrency(salesContract.smallChangeAmount, true)"
                  :check-value="salesContract.withoutSmallChange" :editable="editMode" width="200px"
                  @update:check-value="val => salesContract.withoutSmallChange = val" />
              </div>

              <div v-if="editMode" class="amount-item"
                style="margin: 4px 0; padding-top: 0px; padding-bottom: 8px; border-bottom: 1px solid #ebeef5;">
                <span class="label right-align" style="font-size: 16px; font-weight: bold; color: #606266 ;">合计: </span>
                <span class="value left-align" style="font-size: 16px; font-weight: bold; color: #E64D4D;">
                  {{ formatCurrency(salesContract.totalMount.value) }}
                </span>
              </div>

              <div v-if="editMode" class="amount-item">
                <span class="label right-align" style="font-size: 16px; font-weight: bold; color: #606266 ;">收款信息
                </span>
              </div>

              <div class="amount-item">
                <span class="label right-align">预收冲抵:</span>
                <value-checkbox-widget class="value left-align" :display-text="preOffsetText"
                  :check-value="salesContract.enablePreReceiveOffset" :editable="editMode" width="200px"
                  @update:check-value="val => salesContract.enablePreReceiveOffset = val">
                  <span v-if="editMode">{{ "冲抵" + salesContract.preReceiveOffset.value }}</span>
                </value-checkbox-widget>
              </div>

              <div class="amount-item">
                <span class="label right-align">本次收款:</span>
                <div class="value left-align">
                  <input-cell :width="'200px'" :readonly="!editMode" :model-value="salesContract.payedMount.value"
                    :numberMode="true" :precision="fundPrecision"
                    @update:model-value="val => salesContract.payedMount = new CsFundDouble(val)" />
                </div>
              </div>

              <div v-if="salesContract.payedMount.value != 0" class="amount-item">
                <span class="label right-align">收款账户:</span>
                <div class="value left-align" style="width: 200px;">
                  <fund-account-select :readonly="!editMode" v-model="salesContract.fundAccount" prop="fundAccount"
                    :fund-ui-action="fundUiAction" />
                </div>
              </div>

              <div v-if="editMode" class="amount-item" style="margin: 4px 0; padding-top: 0px; padding-bottom: 8px; ">
                <span class="label right-align" style="font-size: 14px; font-weight: bold; color: #606266 ;">剩余应收:
                </span>
                <span class="value left-align" style="font-size: 14px; font-weight: bold; color: #E64D4D;">
                  {{ formatCurrency(salesContract.remainAmount.value) }}
                </span>
              </div>




              <div v-if="!editMode" class="amount-item">
                <span class="label right-align">应收款:</span>
                <span class="value left-align">{{ formatCurrency(salesContract.totalMount.value) }}</span>
              </div>

              <div v-if="!editMode" class="amount-item">
                <span class="label right-align">实收款:</span>
                <span class="value left-align">{{ formatCurrency(salesContract.totalPayedMount(editMode).value)
                }}</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12" class="other-info-col">
          <!-- Other Information Group -->
          <el-card class="other-info-card" shadow="never">
            <template #header>
              <div class="card-header">
                <div class="title-wrapper">
                  <span class="title-text">其他信息</span>
                </div>
              </div>
            </template>

            <el-descriptions v-if="!editMode" :column="1">
              <el-descriptions-item v-if="latestUpdateInfo" label="最近更新">{{ latestUpdateInfo
              }}</el-descriptions-item>
              <el-descriptions-item label="制单人">{{ docMaker }}</el-descriptions-item>
              <el-descriptions-item label="备注">
                <div class="remark-content">{{ salesContract.remark || '-' }}</div>
              </el-descriptions-item>
            </el-descriptions>

            <!-- 注意本处增加一个div , 不然第一个控件左对齐有问题，具体问题待查  -->
            <div> </div>

            <!-- 备注 -->
            <!-- 
              <div v-if="editMode" class="amount-item">
                <span class="label right-align">备注:</span>
                <input-cell class="value left-align" :width="'400px'" :readonly="!editMode"
                  :model-value="formData.remark"  :remarkMode="true"
                  @update:model-value="val => formData.remark = val" />
              </div>
              -->

            <!-- 备注 -->
            <input-widget-web class="value left-align" v-if="editMode" v-model="formData.remark" label="备注"
              prop="remark" placeholder="请输入备注信息" :remarkMode="true" />
          </el-card>
        </el-col>
      </el-row>


      <!-- 底部操作栏 (仅在编辑模式下显示) -->
      <bottom-bar :visible="editMode">
        <template #left>
          <span class="doc-maker-info">制单人: {{ docMakerBottmBar }}</span>
        </template>
        <template #right>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </template>
      </bottom-bar>

      <!-- 商品选择弹窗 -->
      <subcommodity-select-dialog ref="commoditySelectDialog" :basic-ui-action="basicUiAction"
        @select="handleCommoditySelect" />
    </div>
  </div>
</template>

<script>
import { SalesContract } from '../../public/engine/sales/salesContract'
import { CommodityBatchWithTax } from '../../public/engine/sales/sales'
import { Employee } from '../../public/engine/enterpriseMgt/employee'
import { CsDouble } from '../../public/engine/common/csDouble'
import { CsFundDouble } from '../../public/engine/common/csFundDouble'
import { CommonOrderStatus } from '../../public/engine/common/docDefinition'
import { SalesUiAction } from '../../public/engine/uiAction/salesUiAction'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { Util } from '../../public/utils/util'
import { DateUtil } from '../../public/utils/dateUtil'
import { Engine } from '../../public/engine/engine'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction.js'
import { ActionResult, ActionResultType } from '../../public/engine/common/actionResult.js'
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue'
import PartnerSelect from '../../public/views/componentsWeb/PartnerSelect.vue'
import WarehouseSelect from '../../public/views/componentsWeb/WarehouseSelect.vue'
import DateTimeSelect from '../../public/views/componentsWeb/DateTimeSelect.vue'
import EmployeeSelect from '../../public/views/componentsWeb/EmployeeSelect.vue'
import QualityInputCell from '../../public/views/componentsWeb/QualityInputCell.vue'
import ValueCheckboxWidget from '../../public/views/componentsWeb/ValueCheckboxWidget.vue'
import InputCell from '../../public/views/componentsWeb/InputCell.vue'
import SubcommoditySelectDialog from '../../views/inventory/subcommoditySelectDialog.vue'
import BottomBar from '../../public/views/componentsWeb/BottomBar.vue'
import EventBus from '../../public/engine/ipc/eventBus'
import TabUtil from '@/plugins/tab'
import { MessageUtil } from '@/utils/MessageUtil'
import { Definition } from '../../public/engine/common/definition.js'
import FundAccountSelect from '../../public/views/componentsWeb/FundAccountSelect.vue'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'

export default {
  name: 'contract',
  components: {
    InputWidgetWeb,
    PartnerSelect,
    WarehouseSelect,
    DateTimeSelect,
    EmployeeSelect,
    QualityInputCell,
    InputCell,
    SubcommoditySelectDialog,
    BottomBar,
    ValueCheckboxWidget,
    FundAccountSelect
  },

  data() {
    return {
      salesContract: SalesContract.empty({
        operator: Engine.profile?.nickName,
        operatorId: Engine.profile?.id
      }),
      orgSalesContract: SalesContract.empty({
        operator: Engine.profile?.nickName,
        operatorId: Engine.profile?.id
      }),
      basicUiAction: new BasicUiAction(),
      salesUiAction: new SalesUiAction(),
      inventoryUiAction: new InventoryUiAction(),
      enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
      loading: false,
      CommonOrderStatus,
      SalesContract,
      CsDouble,
      CsFundDouble,
      editMode: false,
      orderId: "",
      formData: {
        docCode: '',
        title: '',
        targetObject: null,
        warehouse: null,
        operateDate: null,
        operator: null,
        remark: '',
        updator: null,
        docMaker: null,
      },
      // 返回数据
      retValue: null,
      selectedCommodities: [],
      submitting: false, // 添加提交状态标识
      fundUiAction: new FundUiAction()
    }
  },

  mounted() {
    this.retValue = null;
    this.orderId = (this.$route.params.id || this.$route.query.id) || "";

    if (!Util.isEmpty(this.orderId)) {
      this.loadSalesContractData();
    } else {
      this.editMode = true;
      this.syncFormData();
    }
  },
  beforeUnmount() {
    if (this.retValue) {
      EventBus.emit('salesContractUpdated', null);
      this.retValue = null;
    }
  },

  deactivated() {
    if (this.retValue) {
      EventBus.emit('salesContractUpdated', null)
      this.retValue = null;
    }
  },

  computed: {
    latestUpdateInfo() {
      return (this.salesContract.updateor && this.salesContract.updateDate) ?
        (this.salesContract.updateor + "  " + DateUtil.getDayTitle(this.salesContract.updateDate)) : null;
    },

    docMaker() {
      return (this.salesContract.id && this.salesContract.docMaker && this.salesContract.recordDate) ?
        (this.salesContract.docMaker + "  " + DateUtil.getDayTitle(this.salesContract.recordDate)) : null
    },

    docMakerBottmBar() {
      return Engine.profile?.nickName.isEmpty
        ? Engine.profile?.userName
        : Engine.profile?.nickName;
    },

    countPrecision() {
      return Definition.precision;
    },

    fundPrecision() {
      return Definition.fundPrecision;
    },

    disCountRation() {
      return Definition.gConstDiscountRatePrecision;
    },

    preOffsetText() {
      return this.editMode ? "余额:" + Util.getFundString(this.salesContract.customerPreRecieveAmount - this.salesContract.preReceiveOffset.value)
        : this.formatCurrency(this.salesContract.preReceiveOffset.value, true);
    }

  },

  methods: {
    syncFormData() {
      this.formData = {
        docCode: this.salesContract.docCode,
        title: this.salesContract.title,
        targetObject: this.salesContract.targetObject,
        warehouse: this.salesContract.wareHouse,
        operateDate: this.salesContract.operateDate,
        operator: new Employee({ id: this.salesContract.operatorId, name: this.salesContract.operator }),
        remark: this.salesContract.remark,
        updator: (this.salesContract.updateor && this.salesContract.updateDate) ?
          (this.salesContract.updateor + "  " + DateUtil.getDayTitle(this.salesContract.updateDate)) : null,
        docMaker: (this.salesContract.id && this.salesContract.docMaker && this.salesContract.recordDate) ?
          (this.salesContract.docMaker + "  " + DateUtil.getDayTitle(this.salesContract.recordDate)) : null,
      };
    },

    fillWithFormData() {
      this.salesContract.title = this.formData.title;
      this.salesContract.targetObject = this.formData.targetObject;
      this.salesContract.wareHouse = this.formData.warehouse;

      // formData.operateDate 控件变更日期会转换为字符串，这里需要转换回Date对象
      if (!(this.formData.operateDate instanceof Date)) {
        this.salesContract.operateDate = DateUtil.strToDate(this.formData.operateDate);
      } else {
        this.salesContract.operateDate = this.formData.operateDate;
      }

      this.salesContract.setOperator({
        operator: this.formData.operator.name,
        operatorId: this.formData.operator.id
      });
      this.salesContract.remark = this.formData.remark;
    },

    // 商品选择 items 类型 SubCommodityInventorySumData
    handleCommoditySelect(items) {
      if (items && items.length > 0) {
        for (let commodity of items) {
          // 检查商品是否已存在
          const exists = this.salesContract.commmodityList.some(
            item => item.commodity.id === commodity.subCommodity.id
          );

          if (!exists) {
            let batch = new CommodityBatchWithTax({
              commodity: commodity.subCommodity,
              count: new CsDouble(1),
              availableCount: commodity.availableCount,
              inventoryCount: commodity.totalInventoryCount,
              batchPrice: commodity.subCommodity.retailPrice,
              singlePrice: commodity.subCommodity.retailPrice
            });
            this.salesContract.addCommodityBatch(batch);
          } else {
            ElMessage.warning(`商品[${commodity.subCommodity.name}]已存在`);
          }
        }
      }
    },

    handleCopy() {
      this.salesContract = SalesContract.clone(this.salesContract);
      this.salesContract.id = '';
      this.salesContract.orderBeforeEdit = null;
      this.editMode = true;
      MessageUtil.showSuccessMsg("复制完成");
    },

    handlePrint() { },

    handleEdit() {
      this.editMode = true;
    },

    async handleDelete() {
      if (Util.isEmpty(this.salesContract.id)) {
        TabUtil.closePage();
      } else {
        try {
          await ElMessageBox.confirm("确定要删除该销售单据吗？", "删除确认", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });

          this.submitting = true;

          let delResult = await this.salesUiAction.removeSalesOrder({
            orderId: this.salesContract.id,
            docType: this.salesContract.docType
          });

          if (delResult == null) {
            this.retValue = new ActionResult({ type: ActionResultType.Del });
            MessageUtil.showSuccessMsg("删除成功");
            TabUtil.closePage();
          }
        } catch (error) {
          if (error !== 'cancel') {
            console.error("salesContractDetailPage handleDelete error:", error);
            ElMessage.error("删除操作失败");
          }
        } finally {
          this.submitting = false;
        }
      }
    },

    handleAddCommodity() {
      if (this.formData.warehouse == null ||
        this.formData.warehouse.id == null ||
        Util.isEmpty(this.formData.warehouse.id)) {
        MessageUtil.showWarningMsg("请先选择仓库");
        return;
      }

      this.$refs.commoditySelectDialog.open(
        this.salesContract.commmodityList.map(item => ({
          commodity: item.commodity
        })),
        {
          warehouse: this.formData.warehouse
        }
      );
    },

    handleSelectionChange(selection) {
      this.selectedCommodities = selection;
    },

    handleDeleteSelectedCommodities() {
      if (this.selectedCommodities.length === 0) {
        ElMessage.warning('请至少选择一个商品进行删除');
        return;
      }

      // 删除选中的商品
      this.selectedCommodities.forEach(commodity => {
        this.salesContract.removeCommodityBatch(commodity);
      });

      // 清空选中
      this.selectedCommodities = [];
    },

    // 取消编辑
    handleCancel() {
      this.salesContract = SalesContract.clone(this.orgSalesContract);
      this.editMode = false;
    },

    async handleSubmit() {

      try {
        // First validate the form
        await this.$refs.ruleFormRef.validate();
        // 验证表单
        const validationError = this.salesContract.validateOrder();
        if (validationError) {

          if (validationError.errorMsg) {
            if (validationError.msgBoxConfirm) {
              try {
                await ElMessageBox.confirm(
                  validationError.errorMsg,
                  '信息错误',
                  {
                    confirmButtonText: '确认',
                    type: 'error'
                  }
                );

                // 错误信息直接返回
                return;

              } catch (confirmError) {
                // User cancelled
                this.submitting = false;
                return;
              }
            }
            else {

              ElMessage.error(validationError.errorMsg);
              return;
            }
          }
          else if (validationError.warningMsg) {
            if (validationError.msgBoxConfirm) {
              try {
                await ElMessageBox.confirm(
                  validationError.warningMsg,
                  '确认提交',
                  {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }
                );

              } catch (confirmError) {
                // User cancelled
                this.submitting = false;
                return;
              }
            }
            else {

              ElMessage.error("validationError.errorMsg");
              return;
            }
          }


        }

        this.submitting = true;
        this.fillWithFormData();
        //console.log('提交销售单数据', this.salesContract);

        //ElMessage.error("校验测试，暂不提交!");
        //return;

        const orderResult = await this.salesUiAction.updateOrCreateSalesContract(this.salesContract, true);

        if (orderResult) {
          if (Util.isEmpty(this.salesContract.id)) {
            this.retValue = new ActionResult({ type: ActionResultType.New });
          } else {
            this.retValue = new ActionResult({ type: ActionResultType.UpdateCommon });
          }
        }

        if (orderResult) {
          // 刷新订单页面
          ElMessage.success("提交保存成功");
          this.orderId = orderResult.id;
          this.editMode = false;
          this.loadSalesContractData();
        }
      } catch (error) {
        console.error('保存失败', error);
        ElMessage.error("保存失败");
      } finally {
        this.submitting = false;
      }
    },

    async loadSalesContractData() {
      try {
        this.loading = true;
        const res = await this.salesUiAction.getSalesDetailInfo(this.orderId);

        if (res) {
          this.salesContract = res;
          this.orgSalesContract = SalesContract.clone(res);
          this.syncFormData();
        } else {
          ElMessage.error('获取销售单详情失败');
        }
      } catch (error) {
        console.error('加载销售单数据失败:', error);
        ElMessage.error('加载销售单数据失败');
      } finally {
        this.loading = false;
      }
    },

    formatCount(value, withSignal = false) {
      return Util.getCountString(value, null, { withPrePositiveNegtiveSignal: withSignal });
    },

    formatCurrency(value, readOnlyZeroDashLine = false) {

      return Util.getFundString(value, { zeroDashLine: readOnlyZeroDashLine && !this.editMode });
    }
  }
}
</script>

<style scoped>
.summary-row {
  margin-bottom: 16px;
  display: flex;
  align-items: stretch;
}

.summary-row .el-col {
  display: flex;
  flex-direction: column;
}

.summary-row .el-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.summary-row .el-card .el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* For the other info card specifically, we need to make its content stretch */
.other-info-card .el-card__body>*:first-child {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* Add these styles to the existing ones */
.amount-summary-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.amount-item {
  display: flex;
  align-items: center;
}

.amount-item .label.right-align {
  text-align: right;
  flex: 0 0 100px;
  /* Fixed width for labels */
  color: #606266;
  margin-right: 12px;
  font-size: 13px;
}

.amount-item .value.left-align {
  text-align: left;
  flex: 1;
  /* Take remaining space 
  font-weight: bold;
  */
  font-size: 13px;
}

.amount-item .total-amount .value.left-align {
  color: #E64D4D;
  font-size: 16px;
}

.sales-contract-detail-container {
  padding: 16px;
  padding-bottom: 80px;
  /* 留出bottom bar的空间 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 0px;
  padding: 0 16px;
}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.summary-container {
  flex: 1;
  min-width: 300px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.total-info {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.store-name {
  font-size: 12px;
  color: #606266;
}

.title-text {
  font-size: 16px;
  font-weight: bold;
}

.status-tag {
  margin-left: 12px;
}

.commodity-image {
  width: 40px;
  height: 40px;
  margin-right: 12px;
}

.remark-content {
  white-space: pre-wrap;
  word-break: break-all;
}

.info-card,
.items-card,
.amount-summary-card,
.other-info-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  padding: 0px 0;
}

.amount-item .label {
  color: #606266;
}

.amount-item .value {
  font-weight: bold;
}

.total-amount .value {
  color: #E64D4D;
  font-size: 16px;
}
</style>